﻿using System;
using System.Windows.Forms;
using System.IO;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Configuration;
using System.Text;

namespace PDFProtect
{
    public partial class Form1 : Form
    {
        const String BLANK = " ";
        const String DOT = ".";
        Int32 status = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Permission.initializeCheckedItems(checkedListBox1);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                StringBuilder textBox1StringBuilder = new StringBuilder();
                if (openFileDialog1.FileName.Length == 1)
                {
                    textBox1StringBuilder.AppendFormat("Selected {0} files.", openFileDialog1.FileNames.Length.ToString());
                }
                else
                {
                    textBox1StringBuilder.AppendFormat("Selected {0} file.", openFileDialog1.FileNames.Length.ToString());
                }
                textBox1.Text = textBox1StringBuilder.ToString();
                status += 1;
                textBox1.BackColor = System.Drawing.Color.Green;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                StringBuilder textBox2StringBuilder = new StringBuilder();
                textBox2StringBuilder.AppendFormat("Output directory : {0}", folderBrowserDialog1.SelectedPath);
                textBox2.Text = textBox2StringBuilder.ToString();
                textBox2.BackColor = System.Drawing.Color.Green;
                status += 1;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (status >= 2)
            {
                String[] sourceFilePaths = openFileDialog1.FileNames;
                String destionationPath = folderBrowserDialog1.SelectedPath;
                Int32 exportPermissions = Permission.getPermission(checkedListBox1);
                foreach (String sourceFilePath in sourceFilePaths)
                {
                    String sourceFileName = Path.GetFileNameWithoutExtension(sourceFilePath);
                    protectPdf(sourceFilePath, Path.Combine(destionationPath, sourceFileName + "_protected.pdf"), Permission.getPermission(checkedListBox1));
                }
                StringBuilder finishedString = new StringBuilder();
                finishedString.AppendFormat("Finished at {0}", System.DateTime.Now);
                button3.Text = finishedString.ToString();
            }
            else
            {
                button3.Text = "Error : You must select file(s) and export directory !";
            }
        }

        private void protectPdf(String source, String destination, Int32 permision)
        {
            if (!Permission.isPasswordProtected(source))
            {
                try
                {
                    using (Stream input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (Stream output = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            PdfReader reader = new PdfReader(input);
                            String[] tempItem = new String[2];
                            // Get the password from "App.config" and encrypt the pdf file.
                            try
                            {
                                PdfEncryptor.Encrypt(reader, output, true, null, ConfigurationManager.AppSettings["PASSWORD"], permision);
                                tempItem[0] = source;
                                tempItem[1] = "FINISHED";
                                listView1.Items.Add(new ListViewItem(tempItem));
                            }
                            catch (Exception e)
                            {
                                tempItem[0] = source;
                                tempItem[1] = e.Message;
                                listView1.Items.Add(new ListViewItem(tempItem));
                            }

                        }
                    }
                }
                catch (Exception e)
                {
                    button3.Text = "Please re-open program because " + e.Message;
                }
            }
            
        }
    }
}
